# python-resmon - Python tools for Resmon monitoring and the Circonus API
# Copyright (c) 2010 Crown coypright
# 
# This file is part of python-resmon.
# 
# python-resmon is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# 
# python-resmon is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
# 
# You should have received a copy of the GNU General Public License
# along with python-resmon.  If not, see <http://www.gnu.org/licenses/>.

import re
import time

from bot import BotPlugin

from circonus.api import CirconusAPI

from checker.checker import ParallelResmonChecker
from checker.translator import AlertFormatter


class ColourScheme(object):
    # Subclasses should populate this with colour names
    SCHEME = {}

    def wrap(self, code, str):
        raise NotImplementedError("Subclasses must implement this method")

    def __getattr__(self, key):
        try:
            code = self.SCHEME[key]
        except KeyError:
            raise AttributeError(key)

        def __format_colour(s):
            return self.wrap(code, s)

        return __format_colour


class IRCColourScheme(ColourScheme):
    SCHEME = {
        'red': 4,
        'yellow': 8,
        'grey': 15,
        'green': 3,
        'lime': 9,
    }

    def wrap(self, code, str):
        return '\x03%02d%s\x03' % (code, str)


class CirconusPlugin(BotPlugin):
    def __init__(self):
        self.api = CirconusAPI.from_config()
        self.lastpoll = int(time.time())
        #self.formatter = AlertFormatter()

    def good_emoticon(self):
        return random.choice([''] * 30 + [':)', ':D', ';)', 'w00t!', 'teh awesome', 'fuckin A', 'Wizard!', 'Splendid!', 'OMG I creamed my pants.'])

    def bad_emoticon(self):
        return random.choice([''] * 30 + [':/', ':(', ':|', 'Oh noes!', 'FUCK!', 'Arse!', 'Bogus', 'Ozzard muck', 'You cunt.'])

    def poll(self):
        alerts = self.api.list_alerts(start=self.lastpoll)
        self.lastpoll = int(time.time())
        batch = []
        for a in alerts:
            hostname = re.sub(r'\s+\(resmon:.*?\)', '', a.check_name)
            batch.append((hostname, a.metric_name, a.value, a.has_cleared()))
        #msgs = self.formatter.format_batch(batch)
        #self.formatter.reload()
        return batch

    def handle_message(self, msg):
        if msg.lower() == 'status':
            yield "Fetching status, please wait..."
            cs = ParallelResmonChecker()
            colour = IRCColourScheme()

            have_alerts = False
            for alert in cs.run_checks():
                have_alerts = True
                
                if alert.severity <= 1:
                    yield colour.red(alert)
                elif alert.severity == 2:
                    yield colour.yellow(alert)
                else:
                    yield str(alert)

            if not have_alerts:
                yield "Everything is fine! \o/"
